package com.ww.idiom.activity;

import java.util.ArrayList;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.ww.core.activity.SlideMenuActivity;
import com.ww.idiom.R;
import com.ww.idiom.activity.menu.LeftFragment;
import com.ww.idiom.adapter.StoreAdapter;
import com.ww.idiom.db.IdiomDbHelper;

public class StoreActivity extends SlideMenuActivity {
	private ListView listView;
	private ArrayList<String> list;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context=StoreActivity.this.getActivity();
		
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction("store");
		context.registerReceiver(mBroadcastReceiver, myIntentFilter);
	}
	

	
	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			getStoreList();
		}
	};

	public void initView(View view) {
		setTitle(view, LeftFragment.mTitleName);
		listView = (ListView) view.findViewById(R.id.listView);
		getStoreList();
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				Intent in = new Intent(context, ResultActivity.class);
				in.putExtra("index", arg2);
				in.putStringArrayListExtra("list", list);
				startActivity(in);
			}
		});
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.activity_store, container, false);
		initView(view);
		return view;
	}

	public void getStoreList() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				IdiomDbHelper i = new IdiomDbHelper(context);
				list = i.getStoreList();
				handler.sendEmptyMessage(1);
			}
		}).start();
	}

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (list.size() > 0) {
				StoreAdapter adapter = new StoreAdapter(context, list);
				listView.setAdapter(adapter);
			} else {
				listView.setVisibility(View.GONE);
			}
		};
	};

}
